<template>
  <el-form ref="ruleFormRef"
           :model="formData"
           :rules="rules"
           :status-icon="showStatusIcon"
           class="login-form"
           size="large"
           @submit.prevent="handleSubmit">

    <el-form-item prop="phone">
      <el-input v-model="formData.phone" placeholder="请输入账号">
        <template #prefix>
          <SvgIcon icon="user-bold" size="15"/>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="formData.password" :show-password="true" placeholder="请输入密码" type="password">
        <template #prefix>
          <SvgIcon icon="lock" size="15"/>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item prop="phrase">
      <el-input v-model="formData.phrase" auto-complete="off" placeholder="验证码" style="width: 66%">
        <template #prefix>
          <SvgIcon icon="valid-code" size="13"/>
        </template>
      </el-input>
      <div class="login-code">
        <img :src="codeData" alt="" @click="handleRefreshCode()">
      </div>
    </el-form-item>

    <el-form-item>
      <el-button :loading="loading" class="btn-long" native-type="submit" type="primary">
        {{ $t('login.login') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import useLoading from '@/hooks/use-loading';
import { useTabsNavStore, useUserStore } from '@/store';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { getCaptchaCode, login, LoginParam } from '@/api/auth-api';
import { debounce } from '@/utils/util.ts';
import { SvgIcon } from '@/components/icon';
import { notification } from '@/hooks/use-message.ts';
import { setToken, setTokenHeader } from '@/utils/auth.ts';

const ruleFormRef = ref<FormInstance>();

// 验证码
const codeData = ref('');
// 表单数据
const formData = reactive<LoginParam>({
  phone: '',
  password: '',
  code: '',
  phrase: ''
});
const {t} = useI18n();
const rules = computed(() => {
  return {
    phone: [{required: true, message: '请输入账号', trigger: 'blur'},],
    password: [{required: true, message: '请输入密码', trigger: 'blur'},],
    phrase: [{required: true, message: '请输入验证码', trigger: 'blur'},],
  };
});

const showStatusIcon = ref(false);
const [loading, setLoading] = useLoading(false);
const userStore = useUserStore();
const tabsNavStore = useTabsNavStore();
const router = useRouter();

// 提交登录请求
const handleSubmit = () => {
  if (loading.value) {
    return;
  }
  ruleFormRef.value?.validate(async (valid) => {
    if (!valid) {
      return;
    }
    setLoading(true);
    try {
      const params: LoginParam = {
        phone: formData.phone,
        password: formData.password,
        code: formData.code,
        phrase: formData.phrase
      }
      // 清空授权信息
      await userStore.clearInfo();
      // 处理登录业务
      const {body} = await login(params,{action:'login'});
      // 设置令牌信息 和 令牌头部
      setToken(body.token);
      setTokenHeader('Authorization');
      // 登录后清理导航栏信息
      tabsNavStore.clear();
      // 进行路由跳转
      await router.push({path: '/'});
      // 通知提示
      // + ' : ' + body.nickname
      notification(t('login.success'), `${t('login.successDesc') }`, {type: 'success', duration: 3500});
    } finally {
      await fetchCode();
      setLoading(false);
    }
  });
};

// 获取验证码
const fetchCode = async () => {
  try {
    const {body} = await getCaptchaCode({action:'info'});
    codeData.value = body.inline;
    formData.code = body.code;
  } catch (error) {
    console.log('error', error);
  }
}

onMounted(() => {
  ruleFormRef.value?.resetFields();
  fetchCode();
})

// 点击验证码更新
const handleRefreshCode = debounce(fetchCode, 100);
</script>

<style lang="scss" scoped>
.login-form {
  max-width: 100%;
  padding: 45px 30px 10px 30px;
  margin: 0 auto;

  .el-form-item {
    margin-bottom: 24px;
  }

  .login-form-auto {
    width: 100%;
    position: relative;
    margin-bottom: 24px;

    :deep(.el-checkbox) {
      height: auto;
    }
  }

  .login-code {
    width: 33%;
    display: inline-block;
    height: 36px;
    margin-left: 3px;

    img {
      border-radius: 3px;
      height: 36px;
      width: 100%;
      cursor: pointer;
    }
  }
}
</style>
